﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using AOP.Filter.Result;
using CacheService.Standard;
using Common.Standard;
using Microsoft.AspNetCore.Mvc;
using MODEL.Model;
using MODEL.View;
using SERVICE.Admin.IService;

namespace Admin.Controllers.System
{

    [Description("系统设置")]
    public class MasterController : Controller
    {
        ISyetemService syetemService;
        ICache cache;
        public MasterController(ISyetemService syetemService,ICache cache)
        {
            this.syetemService = syetemService;
            this.cache = cache;
        }

        [Description("管理员管理"), Native]
        public IActionResult Index()
        {
            return View();
        }
        [Description("管理员管理"), HttpGet]
        public object GetUsers(int page = 1)
        {
            int total;
            int pageSize;
            var list = syetemService.GetManagers(page, out total, out pageSize).Select(x => new { x.id, x.loginName, x.mobile, x.userName, rule = x.SystemRule.name, x.rid });
            return new Page { page = page, total = total, pageSize = pageSize, list = list };
        }
        [Description("添加/修改管理员"), HttpPost]
        public object AddMaster(int id, string loginName, string userName, string mobile, int rid, string pass)
        {
            var master = new MODEL.Model.SystemManager
            {
                loginName = loginName,
                userName = userName,
                rid = rid,
                mobile = mobile,
                pass = pass,
                id = id
            };
            var obj = new SystemManager();
            if (id > 0)
            {
                obj = syetemService.UpdateManager(master);
            }
            else
            {
                obj = syetemService.AddManager(master);
            }
            return new { obj.id, obj.loginName, obj.mobile, obj.userName, rule = obj.SystemRule.name, obj.rid };
        }
        [Description("管理员管理"), HttpGet]
        public object GetRules()
        {
            return syetemService.GetRules().AsParallel().Select(x => new { x.id, x.name }).ToList();
        }
        [Description("删除管理员"), HttpPost]
        public bool Del(int id) {
            var key = Request.Cookies["key"];
            var user = cache.get<SystemManager>(key);
            if (user.id == id) {
                throw new Error("不能删除自身账户");
            }
            return syetemService.DelManager(id);
        }
    }
}